package org.ethereum.net.dpos;

import java.math.BigInteger;

import org.ethereum.util.RLP;
import org.ethereum.util.RLPList;
import org.spongycastle.util.encoders.Hex;

public class VotePresidentResponse extends DPOSMessage {

	private final long round;
	
	private final byte candicate;
	
	private final byte[] electionId;
	
	public VotePresidentResponse(final byte[] encoded) {
		super(encoded);
		
		RLPList paramsList = (RLPList) RLP.decode2(encoded).get(0);
		this.responseCode = ResponseCode.code(RLP.decodeInt(paramsList.get(0).getRLPData(), 0));
		this.round = new BigInteger(1, paramsList.get(1).getRLPData()).longValue();
		if (round < 1) {
	    		throw new IllegalArgumentException("round must be greater then from 1!");
	    }
		byte[] canData = paramsList.get(2).getRLPData();
        this.candicate = canData != null && canData.length > 0 ? RLP.decodeOneByteItem(canData, 0) : 0;
        this.electionId = paramsList.get(3).getRLPData();
	}
	
	public VotePresidentResponse(final long round, final byte candicate, final byte[] electionId, ResponseCode code) {
		super(null);
        this.round = round;
        if (round < 1) {
	    		throw new IllegalArgumentException("round must be greater then from 1!");
	    }
        this.candicate = candicate;
        this.electionId = electionId;
        this.responseCode = code;
        encode();
    }
	
	private void encode() {
		byte[] responseCode = RLP.encodeInt(this.responseCode.getCode());
		byte[] round = RLP.encodeBigInteger(BigInteger.valueOf(this.round));
		byte[] candicate  = RLP.encodeByte(this.candicate);
		byte[] electionId  = RLP.encodeElement(this.electionId);
		this.encoded = RLP.encodeList(responseCode, round, candicate, electionId);
		this.parsed = true;
	}
	
	public long getRound() {
		return round;
	}

	public byte getCandicate() {
		return candicate;
	}

	public byte[] getElectionId() {
		return electionId;
	}

	@Override
	public DPOSMessageCodes getCommand() {
		return DPOSMessageCodes.VOTE_PRESIDENT_RESPONSE;
	}

	@Override
	public byte[] getEncoded() {
		return this.encoded;
	}

	@Override
	public Class<?> getAnswerMessage() {
		return null;
	}

	@Override
	public String toString() {
		return "{round: "+round+", candicate: "+candicate+", electionId: "+Hex.toHexString(electionId)+", responseCode: "+responseCode.toString()+" }";
	}

}
